
package demo523;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

    public class DeleteDemo {

        // 数据库连接信息
        private static final String URL = "jdbc:mysql://localhost:3306/usersDb";
        private static final String DB_USERNAME = "root";
        private static final String DB_PASSWORD = "123456";

        /**
         * 删除功能
         */
        public static void main(String[] args) {
            try {
                // 1. 注册（加载）驱动
                Class.forName("com.mysql.cj.jdbc.Driver");

                // 2. 获取数据库连接
                Connection connection = DriverManager.getConnection(URL, DB_USERNAME, DB_PASSWORD);

                // 3. 编写SQL语句
                String sql = "DELETE FROM user WHERE id = ?";

                // 4. 执行SQL语句
                PreparedStatement preparedStatement = connection.prepareStatement(sql);

                // 5. 给问号赋值
                Scanner scanner = new Scanner(System.in);
                System.out.println("请输入要删除的用户ID：");
                int id = scanner.nextInt();

                preparedStatement.setInt(1, id);

                // 6. 执行删除操作
                int rowsAffected = preparedStatement.executeUpdate();

                // 7. 处理结果
                if (rowsAffected > 0) {
                    System.out.println("删除成功！");
                } else {
                    System.out.println("删除失败！");
                }

                // 8. 关闭资源
                preparedStatement.close();
                connection.close();
            } catch (ClassNotFoundException | SQLException e) {
                e.printStackTrace();
            }
        }
    }


